﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace WpfApp_SmartParking.Base;

public class PasswordEx
{
    public static readonly DependencyProperty PasswordProperty =
        DependencyProperty.RegisterAttached(
            "Password",
            typeof(string),
            typeof(PasswordEx),
            new PropertyMetadata(new PropertyChangedCallback(PasswordPropertyChangedCallbackEvent)));

    public static string GetPassword(DependencyObject d)
    {
        return (string)d.GetValue(PasswordProperty);
    }

    public static void SetPassword(DependencyObject d, string value)
    {
        d.SetValue(PasswordProperty, value);
    }

    static bool _IsUpdatePasswordProperty = true;

    public static void PasswordPropertyChangedCallbackEvent(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is PasswordBox)
        {
            PasswordBox passwordBox = (PasswordBox)d;
            string newPassword = (string)e.NewValue;
            passwordBox.PasswordChanged -= PasswordBox_PasswordChanged;
            if (_IsUpdatePasswordProperty)
                passwordBox.Password = newPassword;
            passwordBox.PasswordChanged += PasswordBox_PasswordChanged;
        }
    }

    private static void PasswordBox_PasswordChanged(object sender, RoutedEventArgs e)
    {
        if (sender is PasswordBox)
        {
            PasswordBox passwordBox = (PasswordBox)sender;
            if (passwordBox.Password != GetPassword(passwordBox))
            {
                _IsUpdatePasswordProperty = false;
                SetPassword((DependencyObject)sender, passwordBox.Password);
                _IsUpdatePasswordProperty = true;
            }
        }
    }
}
